import os
import pyPdf
from datetime import datetime

from DataAccess.blp_client import *

def extract_trade_from_CS_PNOTE(file_path):

	if os.path.isfile(file_path):
		file_name = os.path.split(file_path)[1]
		file_prefix = os.path.splitext(file_name)[0]
		file_suffix = os.path.splitext(file_name)[1]
		
		if file_prefix[:17].lower() == 'primenotesconfirm' and  file_suffix[1:].lower() == 'pdf':
			trade_date = None
			ticker = None
			security_type = 'PNOTE'
			trade_type = None
			quantity = None
			cost_price = None
			currency = None
			settle_date = None
			local_price = None
			local_curncy = None
			fx_rate = None
			commission = None
			
			pdf_file = file(file_path, "rb")
			text = pyPdf.PdfFileReader(pdf_file).getPage(0).extractText()
			pdf_file.close()
			
			#trade date
			td_start = text.find('Counterparty Buy/Sell') + len('Counterparty Buy/Sell')
			td_end = text.find('Trade Date')
			if td_start > -1 and td_end > -1 and td_start < td_end:
				trade_date = datetime.strptime(text[td_start:td_end],'%B %d, %Y').date()
			#ticker
			tick_end = text.find('PNote ISIN')
			tick_start = tick_end - 12
			if tick_start > -1 and tick_end > -1:
				ticker = text[tick_start:tick_end]
			#trade_type
			trdtype_start = text.find('Trade Ref') + len('Trade Ref')
			trdtype_end = text.find('Counterparty Buy/Sell')
			if trdtype_start > -1 and trdtype_end > -1 and trdtype_start < trdtype_end:
				trade_type = text[trdtype_start:trdtype_end]
			#quantity
			qty_start = text.find('Spot @ Trade') + len('Spot @ Trade')
			qty_end = text.find('Number of Notes')
			if qty_start > -1 and qty_end > -1 and qty_start < qty_end:
				quantity = int(text[qty_start:qty_end].replace(',',''))
			#cost_price
			itr = text.find(' Total Consideration') - 1
			if itr > -1:
				amt_text = ''
				while True:
					num = text[itr]
					if num == ' ':
						break
					else:
						amt_text = num + amt_text
						itr += -1
				if quantity:
					cost_price = float(amt_text.replace(',','')) / quantity
			#currency
			curncy_start = text.find('for equity participation notes.')
			if curncy_start > -1:
				curncy_start += len('for equity participation notes.') + 3
				curncy_end = curncy_start + 3
				currency = text[curncy_start:curncy_end]
			#settle_date
			sd_end = text.find('Settlement Date')
			itr = sd_end - 1
			if itr > -1:
				num_of_null = 0
				while True:
					if text[itr] == ' ':
						num_of_null += 1
					if num_of_null == 3:
						break 
					itr += -1
				sd_start = itr + 4
				
				settle_date = datetime.strptime(text[sd_start:sd_end],'%B %d, %Y').date()
			#local price
			lprice_start = text.find('On the basis on the following Parameters:') + len('On the basis on the following Parameters:')
			lprice_end = text.find('Gross Share Price 1')
			if lprice_start > -1 and lprice_end > -1 and lprice_start < lprice_end:
				local_price = float(text[lprice_start:(lprice_end - 3)].strip())
				local_curncy = text[(lprice_end - 3):lprice_end].strip()
			#fx rate
			fx_start = text.find('Gross Share Price 1') + len('Gross Share Price 1')
			fx_end = text.find('FX Rate')
			if fx_start > -1 and fx_end > -1 and fx_start < fx_end:
				fx_rate = float(text[fx_start:(fx_end - 7)].strip())		
			#commission
			commission_start = text.find('Gross Parity Per Unit') + len('Gross Parity Per Unit')
			commission_end = text.find('Commission')
			if commission_start > -1 and commission_end > -1 and commission_start < commission_end:
				commission = float(text[commission_start:(commission_end - 3)].strip().replace(',','').replace('(','').replace(')',''))		

			if trade_date and ticker:
				return [[trade_date, ticker, trade_type, quantity, cost_price, currency, security_type, settle_date, 
						local_price, local_curncy, fx_rate, commission, None, None, None, None, 'CS']]
			
		else:
			raise RuntimeError() + 'File is not CS confirmation:' + file_name	
	else:
		raise RuntimeError() + 'File does not exist:' + file_path
		
def extract_trade_from_CS_HShares(file_path):

	if os.path.isfile(file_path):
		file_name = os.path.split(file_path)[1]
		file_prefix = os.path.splitext(file_name)[0]
		file_suffix = os.path.splitext(file_name)[1]
		
		if file_prefix[:12].lower() == 'emb_cman_nja' and  file_suffix[1:].lower() == 'pdf':
			trade_date = None
			ticker = None
			security_type = 'STOCK'
			trade_type = None
			quantity = None
			cost_price = None
			currency = 'HKD'
			settle_date = None
			local_price = None
			commission = None
			levy = None
			stamp = None
			trdfee = None
			
			pdf_file = file(file_path, "rb")
			text = pyPdf.PdfFileReader(pdf_file).getPage(0).extractText()
			text = text.replace(' ','')
			pdf_file.close()
			
			#trade date
			td_start = text.find('TRADEDATE:') + len('TRADEDATE:')
			td_end = text.find('SETTLEMENTDATE:')
			if td_start > -1 and td_end > -1 and td_start < td_end:
				trade_date = datetime.strptime(text[td_start:td_end].strip(),'%d%B%Y').date()
			#ticker
			isin_start = text.find('ISINCODE:') + len('ISINCODE:')
			isin_end = text.find('SEDOLCODE:')
			if isin_start > -1 and isin_end > -1 and isin_start < isin_end:
				isin = text[isin_start:isin_end] + ' HK Equity'
				ticker = query_blp_data([isin], ['TICKER_AND_EXCH_CODE'])[isin]['TICKER_AND_EXCH_CODE'] + ' Equity'
			#trade_type
			trdtype_start = text.find('WECONFIRMHAVING') + len('WECONFIRMHAVING')
			trdtype_end = text.find('FORYOU')
			if trdtype_start > -1 and trdtype_end > -1 and trdtype_start < trdtype_end:
				trade_type = 'BUY' if text[trdtype_start:trdtype_end] == 'BOUGHT' else 'SELL'	
			#quantity
			qty_start = text.find('QUANTITY:') + len('QUANTITY:')
			qty_end = text.find('PRICE:')
			if qty_start > -1 and qty_end > -1 and qty_start < qty_end:
				quantity = int(text[qty_start:qty_end].replace(',',''))
			#cost_price
			#amt_start = text.find('NET AMOUNT:HKD') + len('NET AMOUNT:HKD')
			amt_start = text.find('NETAMOUNT:HKD') + len('NETAMOUNT:HKD')
			amt_end = text.find('SETTLEMENTDETAILS:')
			if amt_start > -1 and amt_end > -1 and amt_start < amt_end:
				if quantity:
					cost_price = float(text[amt_start:amt_end].replace(',','')) / quantity
			#settle_date
			sd_start = text.find('SETTLEMENTDATE:') + len('SETTLEMENTDATE:')
			sd_end = text.find('SECURITY:')
			if sd_start > -1 and sd_end > -1 and sd_start < sd_end:
				settle_date = datetime.strptime(text[sd_start:sd_end].strip(),'%d%B%Y').date()
			#local price
			lprice_start = text.find('PRICE:') + len('PRICE:')
			lprice_end = text.find('GROSSAMOUNT:')
			if lprice_start > -1 and lprice_end > -1 and lprice_start < lprice_end:
				local_price = float(text[lprice_start:lprice_end].strip().replace(',',''))
			#commission
			commission_start = text.find('COMMISSIONCHARGED:HKD') + len('COMMISSIONCHARGED:HKD')
			commission_end = text.find('LEVYHKD')
			if commission_start > -1 and commission_end > -1 and commission_start < commission_end:
				commission = float(text[commission_start:commission_end].strip().replace(',',''))			
			#levy
			levy_start = text.find('LEVYHKD') + len('LEVYHKD')
			levy_end = text.find('STAMPHKD')
			if levy_start > -1 and levy_end > -1 and levy_start < levy_end:
				levy = float(text[levy_start:levy_end].strip().replace(',',''))				
			#stamp
			stamp_start = text.find('STAMPHKD') + len('STAMPHKD')
			stamp_end = text.find('TRADINGFEEHKD')
			if stamp_start > -1 and stamp_end > -1 and stamp_start < stamp_end:
				stamp = float(text[stamp_start:stamp_end].strip().replace(',',''))						
			#trading fee
			trdfee_start = text.find('TRADINGFEEHKD') + len('TRADINGFEEHKD')
			trdfee_end = text.find('NETAMOUNT:')
			if trdfee_start > -1 and trdfee_end > -1 and trdfee_start < trdfee_end:
				trdfee = float(text[trdfee_start:trdfee_end].strip().replace(',',''))	
	
			if trade_date and ticker:
				return [[trade_date, ticker, trade_type, quantity, cost_price, currency, security_type, settle_date, 
						local_price, None, None, commission, levy, stamp, trdfee, None, 'CS']]
			
		else:
			raise RuntimeError() + 'File is not CS confirmation:' + file_name	
	else:
		raise RuntimeError() + 'File does not exist:' + file_path